#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Node:
     def __init__(self, data):
         self.data = data
         self.next = None


class LinkList:
    def __init__(self):
        self.head = Node(None)

    def is_empty(self):
        """判断链表是否为空"""
        p = self.head   # 头指针
        if p.next == None:
            return True
        return False

    def print_list(self):
        if self.is_empty():
            return None
        p = self.head
        while p:
            print(p.data, end=' ')
            p = p.next
        print()

    def init_list(self, data):
        """初始化链表"""
        self.head = Node(data[0])   # 头结点
        p = self.head
        for i in data[1:]:
            node = Node(i)
            p.next = node
            p = p.next

    def length_list(self):
        """计算链表长度"""
        if self.is_empty():
            return 0
        p = self.head
        cnt = 0
        while p:
            cnt += 1
            p = p.next
        return cnt

    def insert_list(self, n, data):
        """在第n个结点后插入data"""
        if self.is_empty() or n < 0 or n > self.length_list():
            raise IndexError("Index out of link list")
        p = self.head
        index = 1
        while index < n:
            p = p.next
            index += 1
        node = Node(data)
        node.next = p.next
        p.next = node

    def delete_list(self, n):
        """删除第n个结点"""
        if self.is_empty() or n < 0 or n > self.length_list():
            raise IndexError("Index out of link list")
        p = self.head
        index = 1
        pre = p
        while index < n:
            pre = p
            index += 1
            p = p.next
        pre.next = p.next
        p = None

    def get_list(self, n):
        """获取第n个结点的值"""
        if self.is_empty() or n < 0 or n > self.length_list():
            raise IndexError("Index out of link list")
        p = self.head
        index = 1
        while index < n:
            index += 1
            p = p.next
        return p.data


if __name__ == "__main__":
    ll = LinkList()
    data = [1, 4, 5, 8, 2, 3]
    ll.init_list(data)
    ll.insert_list(3, 3)
    ll.print_list()
    ll.delete_list(3)
    ll.print_list()
    print(ll.get_list(3))